/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package data;

import business.Canal;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.sql.SQLException;
import java.sql.ResultSet;

/**
 *
 * @author Mário
 */
public class CanaisData extends CampanhaData {

    public CanaisData() {
        super();
    }

    public int addCanal(String nome,String desc) throws Exception{
       int cod = getnextCodCanal();

        String query = insereCanal(cod,nome,desc);
        st.executeUpdate(query);

        return cod;

    }

    public void removerCanal(int codCanal) throws Exception{

        String query = "DELETE from Canal where cod_canal= "+ codCanal;  
        System.out.println(query);        
        st.executeUpdate(query);

    }

    public ArrayList<Canal> consultarListaCanais() throws SQLException {
        ArrayList<Canal> canais = new ArrayList<Canal>();
        String query = "Select * from Canal";
        System.out.println(query);        
        rs = st.executeQuery(query);
        //boolean resultado = false;
        while(rs.next()){
           // resultado = true;
          canais.add(new Canal(rs.getInt(1),rs.getString(2),rs.getString(3)));
        }

        return canais;
    }

    public void alterarOpcoesCanais(int cod,String nome,String desc) throws SQLException {
        boolean updatenome = !(nome.isEmpty());
        boolean updatedesc = !(desc.isEmpty());
        String query;
        if(updatenome && updatedesc){
        query = "Update Canal SET nomec = '"+nome +"','"+desc+"' where cod_canal="+cod;

        }else if(updatenome){
        query = "Update Canal SET nomec = '"+nome +"'"+" where cod_canal="+cod;
        }else{
        query = "Update Canal SET desch = '"+desc +"'"+" where cod_canal="+cod;
        }
        System.out.println(query);
        res = st.executeUpdate(query);


    }

    public Canal daCanalPorCodigo(int codCanal) throws SQLException {
        Canal canal = null;
        String query = "Select * from Canal where codCanal="+codCanal;
        System.out.println(query);
        rs = st.executeQuery(query);

        while(rs.next()){
         canal = new Canal(rs.getInt(1),rs.getString(2),rs.getString(3));
        }

        return canal;
    }


        public int getnextCodCanal() throws SQLException {

        ResultSet rs;
        int num = 0;

        try {
            rs = st.executeQuery("SELECT MAX(cod_canal) FROM canal");
            rs.next();
            num = rs.getInt(1);
        }
        catch (SQLException e) {

            //
        }
        return(num+1);
    }

    public String insereCanal(int codC, String nome, String descricao){
        return "Insert INTO Canal Values("+codC+",'"+nome+"','"+descricao+"')";


    }
}
